# -*- coding: utf-8 -*-
from win32com import client
import VBAPI
from tkinter import *
from tkinter import ttk, filedialog, messagebox, scrolledtext
import pandas as pd
import traceback
#from . import ChangeFormat as CF


CREO_APP = 'C:/Program Files/PTC/Creo 6.0.4.0/Parametric/bin/parametric.exe'
INPUT_DIR = 'E:/python/test_data-2/'

win = Tk()
win.title("批量参数操作")
win.rowconfigure(0, weight='2')
win.columnconfigure(0, weight='1')

frame1 = ttk.Frame(win, padding='3 3 12 12')
frame1.grid(row=0, column=0, sticky=(N, W, E, S))

ttk.Label(frame1, text="Creo路径", width=15).grid(row=0, column=0, padx=5, pady=5, stick=E)
e_app = ttk.Entry(frame1, width=55)
e_app.grid(row=0, column=1)
e_app.insert('0', CREO_APP)

ttk.Label(frame1, text="文件目录", width=15).grid(row=1, column=0, padx=5, pady=5, stick=E)
e_dir = ttk.Entry(frame1, width=55)
e_dir.grid(row=1, column=1)
e_dir.insert('0', INPUT_DIR)

ttk.Label(frame1, text="参数文件", width=15).grid(row=2, column=0, padx=5, pady=5, stick=E)
e_params = ttk.Entry(frame1, width=55)
e_params.grid(row=2, column=1)

frame2 = ttk.Frame(win, padding='3 3 12 12')
frame2.grid(row=1, column=0, stick=(N, W, E, S))

ttk.Label(frame2, text="修改参数", width=15).grid(row=0, column=0, padx=5, pady=5, stick=W)
ttk.Label(frame2, text="重命名", width=15).grid(row=1, column=0, padx=5, pady=5, stick=W)

st_message = scrolledtext.ScrolledText(frame2, width=150, height=30)
st_message.grid(row=2, column=0, columnspan=10)

def creat_session():
    cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)
    AsyncConnection = cAC.Start(CREO_APP + ' -g:no_graphics -i:rpc_input', '')
    Isession = AsyncConnection.Session
    Isession.ChangeDirectory(INPUT_DIR)
    return Isession

def connect_session():
    cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)
    try:
        AsyncConnection = cAC.Connect(None, None, None, None)
        Isession = AsyncConnection.Session
        print(Isession.ConnectionId)
        Isession.ChangeDirectory(INPUT_DIR)
        return Isession
    except Exception as e:
        st_message.insert('end', '未连接到会话\n')
        st_message.see(END)


def chooseapp():
    filename = filedialog.askopenfilename()
    if filename != "":
        CREO_APP = filename
        e_app.delete('0', 'end')
        e_app.insert('0', CREO_APP)

def choosedir():
    dirname = filedialog.askdirectory()
    if dirname != "":
        INPUT_DIR = dirname
        e_dir.delete('0', 'end')
        e_dir.insert('0', INPUT_DIR)

def chooseparams():
    params = filedialog.askopenfilename(filetypes=(('csv files', '*.csv'), ('excel files', '*.xlsx;*.xls')))
    if params != "":
        e_params.delete('0', 'end')
        e_params.insert('0', params)

def export_excel():
    global df
    data = {'MODEL_NAME': ['', 'part001.prt'],
            "PTC_COMMON_NAME": ['Ex_string', 'test'],
            "MEMBER_NAME": ['Ex_string', 'test'],
            "MATERIAL": ['Ex_string', 'test'],
            "DRAWING_NUMBER": ['Ex_string', 'test'],
            "ENGLISH_NAME": ['Ex_string', 'test'],
            "PDRAWN_BY": ['Ex_string', 'test']}
    df = pd.DataFrame(data)
    filename = INPUT_DIR + 'MultiAddParameter.csv'
    df.to_csv(filename, index=False)
    e_params.delete('0', 'end')
    e_params.insert('0', filename)

def read_excel():
    global df
    if e_params.get() != '':
        filename = e_params.get()
        df = pd.read_csv(filename, sep=',', encoding='gbk', )
        pd.set_option('display.width', None) #设置数据展示宽度
        st_message.insert('end', "参数文件已读取！" + '\n')
        st_message.insert('end', df.iloc[0:])
        st_message.insert('end', '\n')
        st_message.see(END)
    else:
        messagebox.showinfo('提示', '请选择参数文件！')

def add_params():
    global df
    if df.shape[0] > 0:
        try:
            cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)
            AsyncConnection = cAC.Start(CREO_APP + ' -g:no_graphics -i:rpc_input', '')
            Isession = AsyncConnection.Session
            Isession.ChangeDirectory(INPUT_DIR)
            Isession = creat_session()
            st_message.insert('end', '开始添加参数：\n')
            st_message.insert('end', '{0:<25}'.format('Model Name'))
            st_message.see(END)
            #输出参数名
            for i in range(0, df.shape[1]-1):
                para_name = df.iloc[[0], [i+1]].keys()[0]
                st_message.insert('end', '{0:<25}'.format(para_name))
            st_message.insert('end', '\n')

            for i in range(0, df.shape[0] - 1):
                filename = df.iloc[i+1, 0]
                #检索模型
                ModelDescriptor = client.Dispatch(VBAPI.CCpfcModelDescriptor)
                mdlDescr = ModelDescriptor.CreateFromFileName(filename)
                RetrieveModelOptions = client.Dispatch(VBAPI.CCpfcRetrieveModelOptions)
                options = RetrieveModelOptions.Create()
                options.AskUserAboutReps = False
                model = Isession.RetrieveModelWithOpts(mdlDescr, options)

                st_message.insert('end', '{0:<25}'.format(filename))
                for j in range(0, df.shape[1]-1):
                    paraname = df.iloc[[i+1], [j+1]].keys()[0]
                    paratype = df.iloc[0, j+1]
                    paraval = df.iloc[i+1, j+1]
                    if paratype == "Ex_string":
                        iparaval = client.Dispatch(VBAPI.CMpfcModelItem).CreateStringParamValue(paraval)
                    else:
                        iparaval = client.Dispatch(VBAPI.CMpfcModelItem).CreateNoteParamValue(paraval)
                    parameter = model.GetParam(paraname)
                    if parameter != None:
                        if paraname != 'PTC_COMMON_NAME':
                            parameter.Delete()
                            model.CreateParam(paraname, iparaval)
                        else:
                            parameter.Value = iparaval
                    st_message.insert('end', '{0:<25}'.format(paraval))
                model.save()
                st_message.insert('end', '\n')
                st_message.see(END)
                win.update()
            st_message.insert('end', '参数已全部添加')
            st_message.see(END)
        except Exception as e:
            st_message.insert('end', traceback.print_exc())
            st_message.see(END)
        finally:
            if AsyncConnection.IsRunning():
                AsyncConnection.End()
def export_name():
    global df
    try:
        data = {'part_name': [], 'new_name': []}
        namelist = []
        cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)
        AsyncConnection = cAC.Connect(None, None, None, None)
        Isession = AsyncConnection.Session
        Isession.ChangeDirectory(INPUT_DIR)
        model = Isession.GetActiveModel()
        filename = model.FileName
        namelist.append(filename)
        get_modellist(Isession, filename, namelist)
        templist = []
        for i in namelist:
            if i not in templist:
                templist.append(i)
        namelist = templist
        data['part_name'] = namelist
        data['new_name'] = ['']*len(namelist)
        filename = INPUT_DIR + 'Rename.csv'
        df = pd.DataFrame(data)
        df.to_csv(filename, index=False)
        e_params.delete('0', 'end')
        e_params.insert('0', filename)
    except Exception as e:
        st_message.insert('end', traceback.print_exc())
        st_message.see(END)
    finally:
        if AsyncConnection.IsRunning():
            AsyncConnection.Disconnect(None)


def get_modellist(Isession, filename, namelist):
    if Isession:
        Isession = Isession
        model = Isession.GetModelFromFileName(filename)
        items = model.ListFeaturesByType(True, getattr(VBAPI.constants, 'EpfcFEATTYPE_COMPONENT'))
        for item in items:
            item_Descr = item.ModelDescr
            extension = item_Descr.GetExtension()
            namelist.append(item_Descr.GetFileName())
            if extension == 'asm':
                get_modellist(Isession, item_Descr.GetFileName(), namelist)
        return namelist

def read_name():
    pass

def rename():
    global df
    if df.shape[0] > 0:
        try:
            cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)
            AsyncConnection = cAC.Connect(None, None, None, None)
            Isession = AsyncConnection.Session
            Isession.ChangeDirectory(INPUT_DIR)
            # 输出表头
            for i in range(0, df.shape[1]):
                para_name = df.iloc[[0], [i]].keys()[0]
                st_message.insert('end', '{0:<25}'.format(para_name))
            st_message.insert('end', '\n')

            for i in range(0, df.shape[0] - 1):
                filename = df.iloc[i + 1, 0]
                st_message.insert('end', '{0:<25}'.format(filename))
                model = Isession.GetModelFromFileName(filename)
                model.Rename(df.iloc[i+1, 1], True)
                model.save()
                st_message.insert('end', '{0:<25}'.format(df.iloc[i+1, 1]))
                st_message.insert('end', '\n')
                st_message.see(END)
                win.update()
            st_message.insert('end', '已全部重命名')
            st_message.see(END)
        except Exception as e:
            st_message.insert('end', traceback.print_exc())
            st_message.see(END)
        finally:
            if AsyncConnection.IsRunning():
                AsyncConnection.Disconnect(None)




ttk.Button(frame1, text="选择文件", width=15, command=chooseapp).grid(row=0, column=2, padx=5, pady=5)
ttk.Button(frame1, text="选择目录", width=15, command=choosedir).grid(row=1, column=2, padx=5, pady=5)
ttk.Button(frame1, text="选择文件", width=15, command=chooseparams).grid(row=2, column=2, padx=5, pady=5)
ttk.Button(frame2, text="输出模板", width=15, command=export_excel).grid(row=0, column=1, padx=5, pady=5)
ttk.Button(frame2, text="读取参数", width=15, command=read_excel).grid(row=0, column=2, padx=5, pady=5)
ttk.Button(frame2, text="添加参数", width=15, command=add_params).grid(row=0, column=3, padx=5, pady=5)
ttk.Button(frame2, text="输出模板", width=15, command=export_name).grid(row=1, column=1, padx=5, pady=5)
ttk.Button(frame2, text="读取数据", width=15, command=read_excel).grid(row=1, column=2, padx=5, pady=5)
ttk.Button(frame2, text="重命名", width=15, command=rename).grid(row=1, column=3, padx=5, pady=5)

win.mainloop()
